package com.zh.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.exception.BusinessException;
import com.zh.system.domain.dto.AddDicValueDto;
import com.zh.system.domain.dto.UpdateDicValDto;
import com.zh.system.domain.entity.SysDicValue;
import com.zh.system.mapper.SysDicValueMapper;
import com.zh.system.service.SysDicService;
import com.zh.system.service.SysDicValueService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class SysDicValueServiceImpl extends ServiceImpl<SysDicValueMapper, SysDicValue> implements SysDicValueService {
    private final SysDicValueMapper sysDicValueMapper;
    private final SysDicService sysDicService;

    @Override
    public Boolean addDicValue(AddDicValueDto addDicTypeDto) {
        SysDicValue sysDicValue = BeanUtil.copyProperties(addDicTypeDto, SysDicValue.class);
        LambdaQueryWrapper<SysDicValue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDicValue::getDicValue, sysDicValue.getDicValue());
        Integer count = sysDicValueMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("字典值[" + sysDicValue.getDicValue() + "]已存在");
        }
        // 删除缓存
        sysDicService.deleteCache();
        return sysDicValueMapper.insert(sysDicValue) > 0;
    }

    @Override
    public String updateDicValue(UpdateDicValDto updateDicValDto) {
        SysDicValue sysDicValue = BeanUtil.copyProperties(updateDicValDto, SysDicValue.class);
        int i = sysDicValueMapper.updateById(sysDicValue);
        sysDicService.deleteCache();
        return i > 0 ? "修改成功":"修改失败";
    }

    @Override
    public Boolean deleteDicValue(Long id) {
        int i = sysDicValueMapper.deleteById(id);
        sysDicService.deleteCache();
        return i > 0;
    }
}
